package com.google.code.qsecurity.client;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceTokenizer;

public class QChangePasswordPlace extends Place {
	
	public static final String PARAMETER_SEPARATOR = "&";
	public static final String KEY_VALUE_SEPARATOR = "=";
	
	public static final String EMAIL_PARAMETER_NAME = "email";
	public static final String REQUEST_CODE_PARAMETER_NAME = "requestCode";
	
	public static final Map<String, String> parseToken(String token) {
		Map<String, String> map = new HashMap<String, String>();
		if (token != null) {
			String[] params = token.split(PARAMETER_SEPARATOR);
			for (String param : params) {
				String[] keyValues = param.split(KEY_VALUE_SEPARATOR);
				if (keyValues.length > 1) {
					map.put(keyValues[0], keyValues[1]);
				}
			}
		}
		return map;
	}

    private final String email;
    private final String requestCode;

    public QChangePasswordPlace(String email, String requestCode) {
        this.email = email;
        this.requestCode = requestCode;
    }

    private String getEmail() {
		return email;
	}

	private String getRequestCode() {
		return requestCode;
	}

	public static class Tokenizer implements PlaceTokenizer<QChangePasswordPlace> {

        @Override
        public String getToken(QChangePasswordPlace place) {
            return EMAIL_PARAMETER_NAME + KEY_VALUE_SEPARATOR + place.getEmail()
            		+ PARAMETER_SEPARATOR
            		+ REQUEST_CODE_PARAMETER_NAME + KEY_VALUE_SEPARATOR + place.getRequestCode();
        }

        @Override
        public QChangePasswordPlace getPlace(String token) {
        	Map<String, String> params = parseToken(token);
        	return new QChangePasswordPlace(params.get(EMAIL_PARAMETER_NAME),
        			params.get(REQUEST_CODE_PARAMETER_NAME));
        }
    }
    
}
